package rmq

import (
	"errors"
	"gitee.com/sdynasty/clever/clog"
	"github.com/streadway/amqp"
	"sync"
)

type RabbitMQ struct {
	conn *amqp.Connection
	channel *amqp.Channel
}

const QueueName = "clever"
var instance *RabbitMQ
var once sync.Once


func MQInstance() *RabbitMQ {
	once.Do(func() {
		instance = &RabbitMQ{}
		_ = instance.InitConnect()
	})
	return instance
}

func (r *RabbitMQ) InitConnect() error {
	clog.LogLogic().Println("初始化RabbitMQ连接")
	var err error
	r.conn, err = amqp.Dial("")
	if err != nil {
		clog.LogLogic().Errorf("fail to connect rabbitMq:%v", err)
	} else {
		channel, err := r.conn.Channel()
		if err != nil {
			clog.LogLogic().Println("get mqChannel error： ", err)
		} else {
			r.channel = channel
		}
	}

	return err
}

func (r *RabbitMQ) Close() {
	_ = r.channel.Close()
	_ = r.conn.Close()
}

func (r *RabbitMQ) GetMQCon() *amqp.Connection {
	return r.conn
}

func (r *RabbitMQ) GetMQChannel() (*amqp.Channel, error) {
	if r.channel != nil {
		return r.channel, nil
	} else {
		return nil, errors.New("r.channel is nil")
	}
	//return r.channel, nil
	//if r.conn != nil {
	//	channel, err := r.conn.Channel()
	//	if err != nil {
	//		clog.LogLogic().Println("get mqChannel error： ", err)
	//		return nil, err
	//	}
	//	return channel, nil
	//} else {
	//	return nil, errors.New("r.conn is nil")
	//}
}